package cn.xx.user.service.impl;

import cn.xx.basic.constant.PetHomeConstant;
import cn.xx.basic.constant.VerifactionCodeConstant;
import cn.xx.basic.exception.CustomException;
import cn.xx.basic.service.impl.BaseServiceImpl;
import cn.xx.basic.util.HttpClientUtils;
import cn.xx.user.constant.WechatConstant;
import cn.xx.user.domain.LoginInfo;
import cn.xx.user.domain.User;
import cn.xx.user.domain.WechatUser;
import cn.xx.user.dto.UserDto;
import cn.xx.user.mapper.LoginInfoMapper;
import cn.xx.user.mapper.UserMapper;
import cn.xx.user.mapper.WechatUserMapper;
import cn.xx.user.service.IWechatService2;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class WechatService2Impl extends BaseServiceImpl<WechatUser> implements IWechatService2 {

    @Autowired
    private WechatUserMapper wechatUserMapper;

    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;


    @Override
    public Map<String, Object> handleMethod(Map<String, String> map) {
        String code = map.get("code");

        String token_Url = WechatConstant.TOKEN_URL
                .replace("APPID", WechatConstant.APPID)
                .replace("SECRET", WechatConstant.SECRET)
                .replace("CODE", code);

        String jsonUrl = HttpClientUtils.httpGet(token_Url);

        JSONObject jsonObject = JSON.parseObject(jsonUrl);

        String openid = jsonObject.getString("openid");

        String access_token = jsonObject.getString("access_token");

        String user_Url = WechatConstant.USER_URL
                .replace("OPENID", openid)
                .replace("ACCESS_TOKEN", access_token);

        String userJson_Url = HttpClientUtils.httpGet(user_Url);

        jsonObject = JSON.parseObject(userJson_Url);

        WechatUser findWechatUser = wechatUserMapper.findOpenId(openid);

        HashMap<String, Object> resultMap = new HashMap<>();

        if (findWechatUser == null) {
            WechatUser wechatUser = new WechatUser();

            wechatUser.setOpenid(openid);

            wechatUser.setNickname(jsonObject.getString("nickname"));

            wechatUser.setHeadimgurl(jsonObject.getString("headimgurl"));

            wechatUser.setSex(jsonObject.getInteger("sex"));

            wechatUser.setAddress(jsonObject.getString("country"));

            wechatUserMapper.save(wechatUser);

            resultMap.put("openid", openid);

            return resultMap;

        } else {
            LoginInfo logininfo = findWechatUser.getLogininfo();
            if (logininfo == null) {
                resultMap.put("openid", openid);
                return resultMap;
            } else {
                String token = UUID.randomUUID().toString();
                redisTemplate.opsForValue().set("loginUser", logininfo, 30, TimeUnit.MINUTES);
                resultMap.put("token", token);
                resultMap.put("loginUser", logininfo);
                return resultMap;
            }
        }
    }

    @Override
    public Map<String, Object> binder(UserDto userDto) throws CustomException {
        checkData(userDto);
        LoginInfo findloginInfo = loginInfoMapper.checkPhoneAndType(userDto.getPhone(), userDto.getType());
        if (findloginInfo == null) {
            findloginInfo = createLoginInfoByUserDto(userDto);
            loginInfoMapper.save(findloginInfo);
            User user = createUserByLoginInfo(findloginInfo);
            userMapper.save(user);

            wechatUserMapper.binderWechatAndLoginInfo(findloginInfo.getId(), userDto.getOpenid());

        } else {
            wechatUserMapper.binderWechatAndLoginInfo(findloginInfo.getId(), userDto.getOpenid());
        }
        HashMap<String, Object> resultMap = new HashMap<>();
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set("loginUser", findloginInfo, 30 , TimeUnit.MINUTES);
        resultMap.put("token", token);
        resultMap.put("loginUser", findloginInfo);

        return resultMap;
    }

    private User createUserByLoginInfo(LoginInfo loginInfo) {
        User user = new User();
        BeanUtils.copyProperties(loginInfo, user);
        user.setLoginInfo(loginInfo);
        return user;


    }

    private LoginInfo createLoginInfoByUserDto(UserDto userDto) {
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setPhone(userDto.getPhone());
        loginInfo.setType(userDto.getType());
        return loginInfo;
    }

    private void checkData(UserDto userDto) throws CustomException {
        if (StringUtils.isEmpty(userDto.getPhone())) {
            throw new CustomException("手机号必填");
        }
        if (StringUtils.isEmpty(userDto.getCode())) {
            throw new CustomException("验证码必填");
        }

        String codeValue = (String) redisTemplate.opsForValue().get(userDto.getPhone() + ":" + VerifactionCodeConstant.USER_CODE);

        String code = codeValue.split(":")[0];

        if (!code.equals(userDto.getCode())) {
            throw new CustomException("验证码错误");
        }



    }
}
